package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.entity.authority.*;
import com.example.ext.entity.*;
import com.example.ext.jwt.TokenUtils;
import com.example.mapp.*;
import com.example.service.SysUserService;
import com.example.util.*;
import com.github.binarywang.utils.qrcode.QrcodeUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by youkun on 2017/8/13.
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapp userMapp;

    @Autowired
    private Environment environment;

    @Autowired
    private PartyUserMapp partyUserMapp;

    @Autowired
    private SysUserRoleMapp sysUserRoleMapp;

    @Autowired
    private PartyMapp partyMapp;

    @Autowired
    private SystemRoleMapp systemRoleMapp;

    @Autowired
    private SysRoleAuthorMapp sysRoleAuthorMapp;

    @Autowired
    private ElevatorMapp elevatorMapp;

    @Autowired
    private UserCheckMapp userCheckMapp;

    @Autowired
    private PartyCheckMapp partyCheckMapp;

    @Autowired
    InfoAttachmentMapp infoAttachmentMapp;

    @Autowired
    InformationMapp informationMapp;

    @Autowired
	private PromotionMapp promotionMapp;

    @Autowired
    private ImportRecordMapp importRecordMapp;

    @Autowired
    AfterDoMapp afterDoMapp;

    @Autowired
    UserMetastasisMapp userMetastasisMapp;

    @Autowired
    PointFlowMapp pointFlowMapp;


    /**
     * 查询用户列表
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object> findUserList(Long userId) {
        List<ExtSysUser> userList =null;
        List<ExtTree> listMap=null;
        try {
            //查询用户角色的列表
            userList = userMapp.findUserList(userId);
            //放整个树
           listMap = findParent(userList);
        } catch (Exception e) {
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",listMap);
    }


    /**
     * 根据用户名查询用户信息
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> findUserByUserName(SystemUser user) {
        Map<String,Object> map = new HashMap<String,Object>();
//        String lastVersion = environment.getProperty("lastVersion",String.class);
        try {
//            if(!"00000".equals(lastVersion) && "App".equals(user.getAppOrPc())){
//                if(user.getVersion()!=null){
//                    if(Integer.parseInt(lastVersion)>Integer.parseInt(user.getVersion())){
//                        return ResultUtil.returnError("抱歉，您必须更新后才能继续使用",null);
//                    }
//                }else{
//                    return ResultUtil.returnError("抱歉，您必须更新后才能继续使用",null);
//                }
//            }
            ExtSysUser systemUser = userMapp.findUserByUserName(user.getUserName());
            if(systemUser==null){
               return ResultUtil.returnError("用户不存在",null);
            }
            if(!systemUser.getPassword().equals(user.getPassword())){
                return ResultUtil.returnError("密码输入有误",null);
            }
//            if(systemUser.getUserState().equals("0")){
//                return ResultUtil.returnError("账号已停用，请联系管理员",null);
//            }
            systemUser.setPassword("");
            map.put("sysUser",systemUser);
            map.put("token",TokenUtils.generateToken(user));
            systemUser.setVersion(user.getVersion());
            userMapp.updateUserVersion(systemUser);
            try{
                AfterDo afterDo = new AfterDo();
                afterDo.setEventType("4");
                afterDo.setStatus("1");
                AfterDo afterDo1 = afterDoMapp.findByType(afterDo);
                if(null!=afterDo1){
                    map.putAll(afterDo1.toMap());
                }
                return ResultUtil.returnSuccess("成功", map);
            }catch (Exception e){
                logger.error("查询维保场景失败",e);
            }
        } catch (Exception e) {
            logger.error("登陆异常了",e);
            return ResultUtil.returnError("登录失败",null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    //更新 faceUrl
    @Override
    public Map<String, Object> updateFaceUrl(SystemUser systemUser) {
        try {
            userMapp.updateFaceUrl(systemUser);
        } catch (Exception e) {
            logger.error("图像更新失败："+e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("图像更新成功",null);
    }


    @Override
    public Map<String, Object> findSysUserList(ExtSysUser sysUser) {
        List<ExtSysUser> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtSysUser> page = PageHelper.startPage(sysUser.getCurrentPage(), sysUser.getPageSize());
            list = userMapp.findSysUserList(sysUser);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    /**
     * 创建二维码
     * @return
     */
    @Override
    public Map<String, Object> createQrcode(String elevatorId,String elevatorType,String elevatorNum, String partyId) {
        //
        String qrcodUrl = environment.getProperty("qrcodUrl",String.class);
        qrcodUrl += "?elevatorId="+elevatorId+"&elevatorType="+elevatorType+"&elevatorNum="+elevatorNum;
        byte[] bytes = QrcodeUtils.createQrcode(qrcodUrl, 800, null);
        String path = environment.getProperty("upload",String.class);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String dateString = sdf.format(new Date());
        path = path+"qrCodes/"+partyId;//dateString;
        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //重现生成文件名，防止中文乱码
        String fileName = elevatorNum+".png"; //UUID.randomUUID()+".png";
        Path imgPath = FileSystems.getDefault().getPath(path, fileName);
        try {
            Files.write(imgPath, bytes);
            convert(path+File.separator+fileName);
        } catch (IOException e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("创建二维码失败"+e.getMessage(),null);
        }
        Map res = new HashMap();
        res.put("imagePath","qrCodes/"+partyId+"/"+fileName);
        res.put("urlPath",qrcodUrl);
        return ResultUtil.returnSuccess("创建二维码成功",res);
    }

    public static void convert(String path) {
        try {
            BufferedImage image = ImageIO.read(new File(path));
            ImageIcon imageIcon = new ImageIcon(image);
            BufferedImage bufferedImage = new BufferedImage(
                    imageIcon.getIconWidth(), imageIcon.getIconHeight(),
                    BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            g2D.drawImage(imageIcon.getImage(), 0, 0,
                    imageIcon.getImageObserver());
            int alpha = 0;
            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage
                    .getHeight(); j1++) {
                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage
                        .getWidth(); j2++) {
                    int rgb = bufferedImage.getRGB(j2, j1);
                    if (colorInRange(rgb))
                        alpha = 0;
                    else
                        alpha = 255;
                    rgb = (alpha << 24) | (rgb & 0x00ffffff);
                    bufferedImage.setRGB(j2, j1, rgb);
                }
            }
            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
            // 生成图片为PNG
            String outFile = path.substring(0, path.lastIndexOf("."));
            ImageIO.write(bufferedImage, "png", new File(outFile + ".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("生成二维码失败："+e.getMessage(),e);
        }
    }

    public final static int color_range = 230;
    public static boolean colorInRange(int color) {
        int red = (color & 0xff0000) >> 16;
        int green = (color & 0x00ff00) >> 8;
        int blue = (color & 0x0000ff);
        if (red >= color_range && green >= color_range && blue >= color_range)
            return true;
        return false;
    }

    @Override
    public Map<String, Object> upload(MultipartFile file,HttpServletRequest request) {
        if(file.isEmpty()){
            return ResultUtil.returnError("文件不能空",null);
        }
        if(file.getSize()>10485760){
            return ResultUtil.returnError("文件不能大于10MB",null);
        }
        String fileName ="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());
        FileOutputStream out=null;
        BufferedOutputStream outp = null;
        try {

            //从配置文件中读取路径
            String path = environment.getProperty("upload",String.class);

            File file1 = new File(path+dateString);
            if(!file1.exists()){
                file1.mkdirs();
            }
            //重现生成文件名，防止中文乱码
            fileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //创建文件
            File file2 = new File(path + dateString + File.separator + fileName);
            out = new FileOutputStream(file2);
            outp =new BufferedOutputStream(out);
            outp.write(file.getBytes());

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }finally {
            try{
                if(out!=null){
                    out.flush();
                    out.close();
                }
            }catch(Exception e){
                logger.error("文件上传流关闭失败");
            }
            try{
                if(outp!=null){
                    outp.flush();
                    outp.close();
                }
            }catch(Exception e){
                logger.error("文件上传流关闭失败");
            }


        }
        return ResultUtil.returnSuccess("上传文件成功",dateString + "/" + fileName);
    }

    @Override
    @Transactional
    public Map<String, Object> uploadRootData(MultipartFile file,HttpServletRequest request) {
        if(file.isEmpty()){
            return ResultUtil.returnError("文件不能空",null);
        }
        if(file.getSize()>10485760){
            return ResultUtil.returnError("文件不能大于10MB",null);
        }
        String fileName ="";
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String dateString = sdf.format(new Date());
        try {

            //从配置文件中读取路径
            String path = environment.getProperty("upload",String.class);

            File file1 = new File(path);
            if(!file1.exists()){
                file1.mkdirs();
            }
            fileName = "data.xlsx";
            //创建文件
            File file2 = new File(path + File.separator + fileName);
            FileOutputStream out = new FileOutputStream(file2);
            BufferedOutputStream  outp =new BufferedOutputStream(out);
            outp.write(file.getBytes());
            outp.flush();
            outp.close();
            out.flush();
            out.close();

            List<List<Object>> l = ExcelUtil.getListByExcel(new FileInputStream(path + File.separator + fileName),"data.xlsx");
            //处理数据
            List<String> usedPartys = new ArrayList<>();
            List<String> amintPartys = new ArrayList<>();
            List<ExtElevator> elevators = new ArrayList<>();
            Set<String> usedPartyset = new HashSet<>();
            Set<String> amintPartyset = new HashSet<>();
            for (int i=0;i<l.size();i++) {
                ExtElevator elevator = new ExtElevator();
                String[] data = l.get(i).toString().split(",");
                usedPartyset.add(data[5].trim());
                amintPartyset.add(data[13].trim());

                //电梯
                elevator.setElevatorNum(data[4].trim());
                elevator.setOutsideNum("96333");
                elevator.setSerialNum(data[65].trim());
                elevator.setElevatorProvince(data[27].trim());
                elevator.setElevatorCity(data[30].trim());
                elevator.setElevatorArea(data[32].trim());
                elevator.setElevatorStreet(data[34].trim());
                elevator.setElevatorAddr(data[10].trim());
                elevator.setElevatorModel(data[66].trim());
                elevator.setCreateCompanyName(data[62].trim());
                elevator.setExaminationPartyName(data[75].trim());
                elevator.setNextCheckDate(data[6].trim().replaceAll("-",""));
                elevator.setElevatorTypeId(Long.parseLong("1"));
                elevator.setMaintTel(data[67].trim());
                elevator.setPointsNum("0");

                if(data[9].trim().equals("在用")){
                    elevator.setIsStop("0");
                }else if(data[9].trim().equals("停用")){
                    elevator.setIsStop("1");
                }else if(data[9].trim().equals("安装")) {
                    elevator.setIsStop("2");
                }else{
                    elevator.setIsStop("3");
                }

                if("曳引与强制驱动电梯".equals(data[23].trim())) {
                    elevator.setElevatorTypeId(Long.valueOf("1"));
                }else if("自动扶梯与自动人行道".equals(data[23].trim())) {
                    elevator.setElevatorTypeId(Long.valueOf("4"));
                }else if("液压驱动电梯".equals(data[23].trim())) {
                    elevator.setElevatorTypeId(Long.valueOf("2"));
                }else if("杂物电梯".equals(data[23].trim())) {
                    elevator.setElevatorTypeId(Long.valueOf("3"));
                }

                elevator.setRescuePhoneNum("96333");
                elevator.setMaintenancePartyName(data[13].trim());
                elevator.setUsedPartyName(data[5].trim());
                elevators.add(elevator);

            }

            Iterator u = usedPartyset.iterator();
            while(u.hasNext()){
                usedPartys.add(u.next()+"");
            }

            Iterator m = amintPartyset.iterator();
            while(m.hasNext()){
                amintPartys.add(m.next()+"");
            }


            List<String> authList = new ArrayList<>();

            authList.add("1");
            authList.add("5");
            authList.add("86");
            authList.add("87");
            authList.add("88");
            authList.add("89");
            authList.add("6");
            authList.add("90");
            authList.add("91");
            authList.add("8");
            authList.add("92");
            authList.add("93");
            authList.add("94");
            authList.add("11");
            authList.add("95");
            authList.add("96");
            authList.add("97");
            authList.add("98");
            authList.add("12");
            authList.add("13");
            authList.add("9");
            authList.add("10");
            authList.add("99");
            authList.add("100");
            authList.add("14");
            authList.add("15");
            authList.add("16");

            List<String> wbauthList = new ArrayList<>();
            wbauthList.add("1");
            wbauthList.add("5");
            wbauthList.add("86");
            wbauthList.add("87");
            wbauthList.add("88");
            wbauthList.add("6");
            wbauthList.add("89");
            wbauthList.add("90");
            wbauthList.add("91");
            wbauthList.add("11");
            wbauthList.add("96");
            wbauthList.add("12");
            wbauthList.add("13");
            wbauthList.add("9");
            wbauthList.add("10");

            List<String> syauthList = new ArrayList<>();
            syauthList.add("1");
            syauthList.add("5");
            syauthList.add("86");
            syauthList.add("87");
            syauthList.add("88");
            syauthList.add("6");
            syauthList.add("89");
            syauthList.add("90");
            syauthList.add("91");
            syauthList.add("96");
            syauthList.add("11");
            syauthList.add("12");
            syauthList.add("13");
            syauthList.add("9");
            syauthList.add("10");
            syauthList.add("99");
            syauthList.add("100");
            syauthList.add("14");
            syauthList.add("15");
            syauthList.add("16");


            //1 建立分局监管部门
            Party jgParty = new Party();
            jgParty.setPartyName("雨花台区监管部门");
            //jgParty.setPartyType("4");
            int ss = partyMapp.insert(jgParty);

            if(ss>0){
               this.addRoleUser(jgParty, authList);
            }

            Map<String,String> maintMap = new HashMap<>();
            //2 建立维保单位
            for(int i=0;i<amintPartys.size();i++){
                Party maint = new Party();
                maint.setPartyName(amintPartys.get(i));
               // maint.setParentId(jgParty.getId());
               // maint.setPartyType("1");
                int us = partyMapp.insert(maint);

                maintMap.put(maint.getPartyName(),maint.getId()+"");
                if(us>0){
                    this.addRoleUser(maint, wbauthList);
                }
            }


            Map<String,String> usedMap = new HashMap<>();
            //3 建立物业单位
            for(int i=0;i<usedPartys.size();i++){
                Party usedParty = new Party();
                usedParty.setPartyName(usedPartys.get(i));
               // usedParty.setParentId(jgParty.getId());
               // usedParty.setPartyType("2");
                int ms = partyMapp.insert(usedParty);

                usedMap.put(usedParty.getPartyName(),usedParty.getId()+"");
                if(ms>0){
                    this.addRoleUser(usedParty, syauthList);
                }
            }
            //4 建立电梯
            for(int i =0;i<elevators.size();i++){
                ExtElevator extElevator = elevators.get(i);
                extElevator.setMaintenancePartyId(Long.valueOf(maintMap.get(extElevator.getMaintenancePartyName())));
                extElevator.setUsedPartyId(Long.valueOf(usedMap.get(extElevator.getUsedPartyName())));
                elevatorMapp.add(extElevator);
                //二维码生成
                Map<String,Object> map =  createQrcode(extElevator.getId().toString(),extElevator.getElevatorTypeId().toString(),extElevator.getElevatorNum().toString(),usedMap.get(extElevator.getUsedPartyName()));
                if(map.get("status").toString().equals("200")){
                    extElevator.setQrCodeUrl(map.get("data").toString());
                }
                //更新
                elevatorMapp.update(extElevator);
            }


        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("上传文件成功", fileName);
    }


    public void addRoleUser(Party party, List<String> authList ) throws Exception{
        //建角色
        ExtSystemRole systemRole = new ExtSystemRole();
        systemRole.setRoleName("管理员");
        systemRole.setRoleDescribe("本单位的系统管理员");
        systemRole.setList(authList);

        int d = systemRoleMapp.add(systemRole);

        if(d>0){
            //角色 功能关联
            for(int i=0;i<systemRole.getList().size();i++) {
                SysRoleAuthor roleAuthor = new SysRoleAuthor();
                roleAuthor.setAuthorId(Integer.parseInt(systemRole.getList().get(i).toString()));
                roleAuthor.setRoleId(Integer.parseInt(systemRole.getId().toString()));
                sysRoleAuthorMapp.add(roleAuthor);
            }
            //建人员
            ExtSysUser extSysUser = new ExtSysUser();

            List<String> roleList = new ArrayList<>();
            roleList.add(systemRole.getId()+"");

            extSysUser.setRoleList(roleList);
            extSysUser.setPassword("a123456");
            extSysUser.setUserName("admin"+party.getId());
            //extSysUser.setUserNameCn("管理员");
            extSysUser.setPartyId(party.getId());
            this.addUser(extSysUser);
        }
    }

//    public static void main(String args[]){
//
//        String qrcodUrl = "www.baidu.com";
//        byte[] bytes = QrcodeUtils.createQrcode(qrcodUrl, 800, null);
//        String path = "/Users/simon/Desktop/tt";
//
//        File file1 = new File(path);
//        if(!file1.exists()){
//            file1.mkdirs();
//        }
//        //重现生成文件名，防止中文乱码
//        String fileName = "aa.png";
//        Path imgPath = FileSystems.getDefault().getPath(path, fileName);
//        try {
//            Files.write(imgPath, bytes);
//        } catch (IOException e) {
//            logger.error(e.getMessage());
//        }
//
//        convert("/Users/simon/Desktop/tt/aa.png");
//    }

    @Override
    public void getImage(String dateString, String fileName, HttpServletResponse response) {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            //获取图片存放路径
            String imgPath = environment.getProperty("upload",String.class)+dateString+File.separator+fileName;
            ips = new FileInputStream(new File(imgPath));
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
            out.close();
            ips.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void getElevatorImage(String partyId, String fileName, HttpServletResponse response) {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            //获取图片存放路径
            String imgPath = environment.getProperty("upload",String.class)+"qrCodes"+File.separator+partyId+File.separator+fileName;
            ips = new FileInputStream(new File(imgPath));
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
            out.close();
            ips.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> deleteImage(String dateString, String fileName) {
        String imgPath = environment.getProperty("upload",String.class) + dateString + File.separator + fileName;
        File file = new File(imgPath);
        if(file.exists()){
            file.delete();
            return ResultUtil.returnSuccess("删除文件成功",fileName);
        }
        return ResultUtil.returnError("删除文件失败",fileName);
    }


    @Override
    @Transactional
    public Map<String, Object> addUser(ExtSysUser extSysUser) {
        try {
            // 判断userCode是否唯一
            List<SystemUser> userCodeList = userMapp.queryUserCodeList(extSysUser.getUserCode());
            if(userCodeList !=null && userCodeList.size()>0 ){
                throw  new Exception("登录名： "+ extSysUser.getUserCode() +" 已经被使用，请重新输入！" );
            }

            SystemUser s = userMapp.queryByCardNumber(extSysUser.getCardNumber());
            if(null!=s){
                throw  new Exception("身份证号被使用!");
            }
            if (null != extSysUser.getWorkNumber() && !"".equals(extSysUser.getWorkNumber().trim())) {
                SystemUser ss = userMapp.queryByWorkNumber(extSysUser.getWorkNumber());
                if(null != ss){
                    throw  new Exception("工号被使用!");
                }
            }

            //添加用户表
            extSysUser.setUserState("1");
            int i = userMapp.add(extSysUser);
            //添加用户机构关联表
            PartyUser partyUser = new PartyUser();
            partyUser.setUserId(extSysUser.getId()+"");
            partyUser.setPartyId(extSysUser.getPartyId()+"");
            partyUserMapp.insert(partyUser);

            /**
             * 插入用户与角色的关系
             */
            if(extSysUser.getRoleId() != null){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(Integer.parseInt(extSysUser.getRoleId()));
                sysUserRole.setUserId(Integer.parseInt(extSysUser.getId().toString()));
                sysUserRoleMapp.insert(sysUserRole);
            }
            //添加用户和角色的关联
            for(int j=0;j < extSysUser.getRoleList().size();j++){
                if(extSysUser.getRoleList().get(j) != null && extSysUser.getRoleList().get(j)
                .equals(extSysUser.getRoleId())){
                    continue;
                }
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(Integer.parseInt(extSysUser.getRoleList().get(j)));
                sysUserRole.setUserId(Integer.parseInt(extSysUser.getId().toString()));
                sysUserRoleMapp.insert(sysUserRole);
            }

			if (null != extSysUser.getWorkNumber() && !"".equals(extSysUser.getWorkNumber().trim())
					&& null != extSysUser.getEmail() && !"".equals(extSysUser.getEmail().trim())) {
				String to = null;
				try {
					// 发送邮件
					String hostName = environment.getProperty("email.hostName", String.class);
					Integer port = environment.getProperty("email.port", Integer.class);
					String form = environment.getProperty("email.form", String.class);
					String password = environment.getProperty("email.password", String.class);
					to = extSysUser.getEmail();
					String msg = extSysUser.getUserName() + "您好，您的审核结果是：通过。您的账号是：" + extSysUser.getUserCode() + " 密码是：" + extSysUser.getPassword() + "。";
//					EmailUtil.sendEmail(hostName, port, form, to, "电梯动态安全监管系统注册审核结果", msg, password);
				} catch (Exception e) {
					logger.error("根据：" + to + "，邮件发送失败！", e);
				}
			}
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }finally {
            if(! "4".equals(extSysUser.getPartyType())){
                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                //获取注册用户此证情况
                String cardType = extSysUser.getCardType();

                // 判断多证情况
                PointDefend defend = SystemPointUtil.multipleCard(infoCache, cardType, "add_double_cards", "add_one_cards", "add_none_cards");


                Long partyId = extSysUser.getPartyId();
                // 获取当前用户，计算积分
                Map<String, Object> maps = pointFlowMapp.findUserInfo(partyId);
                long mark = (long) maps.get("mark");
                int round = (int) (mark + defend.getMark());
                // 更新积分
                String userId = (String) maps.get("userId");
                int i = pointFlowMapp.updateMark(round, userId);


                String userName = (String) maps.get("userName");
                String partyName = (String) maps.get("partyName");
                String function = "添加";
                SystemPointUtil.insertFlow(pointFlowMapp, i, defend, round, userName, partyName, function);
            }
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> findById(String id) {
        ExtSysUser extSysUser = null;
        try {
            extSysUser = userMapp.findById(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",extSysUser);
    }


    @Override
    @Transactional
    public Map<String, Object> update(ExtSysUser systemUser) {
        try {
//            SystemUser s = new SystemUser();
            //查询数据是否存在
            ExtSysUser system = userMapp.findById(systemUser.getId().toString());
            if(null==system){
                throw new Exception("数据不存在!");
            }
            systemUser.setId(system.getId());
            systemUser.setType(system.getType());
            userMapp.update(systemUser);
            // 查询userCode是否唯一,数据进行回滚
            List<SystemUser> userCodeList = userMapp.queryUserCodeList(systemUser.getUserCode());
            if(userCodeList !=null && userCodeList.size()>1){
                throw new Exception("登录名已经存在，请重新修改!");
            }
            //删除角色和用户的关联
            sysUserRoleMapp.deleteByUserId(systemUser.getId().toString());
            //插入角色和用户的功能

            if(systemUser.getRoleId()!=null){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(Integer.parseInt(systemUser.getRoleId()));
                sysUserRole.setUserId(Integer.parseInt(systemUser.getId().toString()));
                sysUserRoleMapp.insert(sysUserRole);
            }

            //删除机构和用户的关联
            partyUserMapp.deleteByUserId(systemUser.getId().toString());
            //插入机构和用户的功能
            PartyUser partyUser = new PartyUser();
            partyUser.setPartyId(systemUser.getPartyId()+"");
            partyUser.setUserId(systemUser.getId()+"");
            partyUserMapp.insert(partyUser);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("更新用户失败："+e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    @Transactional
    public Map<String, Object> delete(List<String> ids,String partyType,String partyId) {
        try {
            for(String id:ids){
                // 先进行数据查询
                ExtSysUser extSysUser = userMapp.findById(id);

                userMapp.delete(id);
                partyUserMapp.deleteByUserId(id);
                sysUserRoleMapp.deleteByUserId(id);
                userCheckMapp.deleteBySystemUserId(id);

                if (!"4".equals(partyType)) {
                    PointDefendInfoCache infoCache = new PointDefendInfoCache();
                    // 判断多证情况
                    PointDefend defend = SystemPointUtil.multipleCard(infoCache, extSysUser.getCardType(), "add_double_cards", "add_one_cards", "add_none_cards");

                    // 获取当前用户，计算积分
                    Map<String, Object> maps = pointFlowMapp.findUserInfo(Long.valueOf(partyId));

                    // 获取分数
                    long  mark = (long) maps.get("mark");
                    // 计算分数
                    int round = (int) (mark - defend.getMark());
                    // 更新积分
                    String userId = (String) maps.get("userId");
                    int i = pointFlowMapp.updateMark(round, userId);

                    SystemPointUtil.insertFlow(pointFlowMapp, i, defend, round, extSysUser.getUserName(), extSysUser.getPartyName(), "删除一名不持证用户");
                }
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("删除用户失败："+e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     *   查询用户的功能
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> findUserFunction(String id) {
        List<ExtSysUser> userList =null;
        List<ExtTree> listMap=null;
        try {
            userList = userMapp.findUserFunction(id);
            //放整个树
            listMap = findParent(userList);
        } catch (Exception e) {
            logger.error("查询用户的功能："+e.getMessage(),e);
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",listMap);
    }



    /**
     * 查询角色已拥有的树
     */
    @Override
    public Map<String,Object> findUserFunctionByRoleId(String roleId){
        List<ExtSysUser> userList =null;
        try {
            userList = userMapp.findUserFunctionByRoleId(roleId);
        } catch (Exception e) {
            logger.error("查询角色已拥有的树："+e.getMessage(),e);
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",userList);
    }


    /**
     * 查询角色已拥有的全部功能
     */
    @Override
    public Map<String, Object> findFuncSID(String userName) {
        List<String> userList =null;
        try {
            userList = userMapp.findFuncSID(userName);
        } catch (Exception e) {
            logger.error("查询角色已拥有的全部功能："+e.getMessage(),e);
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",userList);
    }

    /***
     * 个人用户注册
     * @param userCheck
     * @return
     */
    @Override
    public Map<String, Object> registerUser(UserCheck userCheck) {
        try {
            /**
             * 处理注册时，字段前后有空格
             */
            userCheck.setUserCode(userCheck.getUserCode().trim());
            userCheck.setCardNumber(userCheck.getCardNumber().trim());
            SystemUser systemUser = userMapp.findUserPartyByUserCode(userCheck.getUserCode().trim());
            if(systemUser!=null){
                return ResultUtil.returnError("用户"+userCheck.getUserCode()+"已存在！",null);
            }
            if(null==userCheck.getRoleId() || "".equals(userCheck.getRoleId().trim())){
                return ResultUtil.returnError("请选择用户角色！",null);
            }
            //查询企业是否存在这个人这里根据名字查询
            //如果根据身份证号没查询到
            SystemUser systemUser1 = userMapp.queryByCardNumber(userCheck.getCardNumber());
            if(systemUser1==null){
                return ResultUtil.returnError("根据身份证号："+userCheck.getCardNumber()+"没有找到该员工，请联系您的单位确认！",null);
            }
            //查看这个人员是否已经注册过了
            if(systemUser1.getUserCode()!=null && systemUser1.getUserCode().length()>0){
                return ResultUtil.returnError("身份证号："+userCheck.getCardNumber()+"已经注册过，请联系您的单位确认！",null);
            }
            UserCheck uc = userCheckMapp.queryByCardNumber(userCheck.getCardNumber());
            if(uc!=null){
                return ResultUtil.returnError("此身份证号："+userCheck.getCardNumber()+" 已经被人注册，请联系超级管理员！",null);
            }
//            //岗位是否对
//            checkPartyPerson.setTypeOfPost(userCheck.getRoleId());
//            PartyPerson p = partyPersonMapp.queryByPartyIdAndUserNameAndTypeOfPost(checkPartyPerson);
//            if(p==null){
//                return ResultUtil.returnError("请选择正确的岗位类型！",null);
//            }
            //设置注册日期
            userCheck.setStartTime(new Date());
            userCheck.setStatus("1");

            userCheckMapp.insert(userCheck);
        }catch (Exception e){
            logger.error("个人用户注册失败："+e.getMessage(),e);
            return ResultUtil.returnError("个人用户注册失败！",null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 个人用户审核
     * @param userCheck
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> checkRegisterUser(UserCheck userCheck) {
        try {
            //查询用户是否存在
            UserCheck userCheck1 = userCheckMapp.queryById(userCheck.getId().toString());
            if(userCheck1==null){
                return ResultUtil.returnError("用户"+userCheck.getUserCode()+"不存在！",null);
            }
            //审核通过才记录到系统中
            if(userCheck.getStatus().equals("2")){
                //用户名密码添加到用户登陆表（sys_user
                ExtSysUser sysUser = new ExtSysUser();
                //个人用户
                sysUser.setType("user");
                sysUser.setUserState("1");
                BeanCopUtil.converJavaBean(sysUser,userCheck1);
                //更行用户
                //根据身份证号查询用户表是否有这个用户
                SystemUser sss  = userMapp.queryByCardNumber(sysUser.getCardNumber());
                if(null!=sss){
                    sysUser.setId(sss.getId());
                }else{
                    return ResultUtil.returnError("用户身份证："+sysUser.getCardNumber()+" 系统中不存在，不能审批！",null);
                }
                userMapp.update(sysUser);
                //设置用户和机构的关联关系
//                PartyUser partyUser = new PartyUser();
//                partyUser.setPartyId(Long.parseLong(userCheck1.getPartyId()));
//                partyUser.setUserId(sysUser.getId());
//                partyUserMapp.insert(partyUser);
                //设置用户和角色

                //先删 后插入
                sysUserRoleMapp.deleteByUserId(sysUser.getId().toString());
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(Integer.parseInt(sysUser.getId().toString()));
                sysUserRole.setRoleId(Integer.parseInt(userCheck1.getRoleId()));
                sysUserRoleMapp.insert(sysUserRole);
                //删除用户的时候也需要删除审核表
                userCheck1.setSystemUserId(sysUser.getId().toString());

                try{
                    if (("5".equals(userCheck1.getRoleId()) ) && sysUser.getFirstgt() != null) {
                        PromotionUtil.addEmpiric(sysUser.getId(), "3", 5, "在个人信息注册中上传资质文件1次", promotionMapp, true);
                    }
                    if (("7".equals(userCheck1.getRoleId()) ) && sysUser.getFirstgt() != null) {
                        PromotionUtil.addEmpiric(sysUser.getId(), "4", 5, "在个人信息注册中上传资质文件1次", promotionMapp, true);
                    }
                    if ("7".equals(userCheck1.getRoleId())) {
                        PromotionUtil.calcParty(promotionMapp, 5, "1", sysUser.getPartyId(), "审批1个注册信息", "0");
                    } else if ("5".equals(userCheck1.getRoleId())) {
                        PromotionUtil.calcParty(promotionMapp, 5, "2", sysUser.getPartyId(), "审批1个注册信息", "0");
                    }
                }catch(Exception e){
                    logger.error("个人审批加分失败"+e.getMessage(),e);
                }

            }

            //更新userCheck1的状态
            userCheck1.setSuccessTime(new Date());
            userCheck1.setStatus(userCheck.getStatus());
            userCheck1.setRemarks(userCheck.getRemarks());
            userCheckMapp.update(userCheck1);

            if(null!=userCheck1.getEmail() && !"".equals(userCheck1.getEmail().trim())){
                String  to = null;
                try{
                    //发送邮件
                    String hostName = environment.getProperty("email.hostName",String.class);
                    Integer port = environment.getProperty("email.port",Integer.class);
                    String  form = environment.getProperty("email.form",String.class);
                    String password = environment.getProperty("email.password",String.class);
                    to  = userCheck1.getEmail();
                    String status =  "";
                    if(userCheck.getStatus().equals("1")){
                        status = "申请中。";
                    }
                    if(userCheck.getStatus().equals("2")){
                        status = "通过。您的账号是："+userCheck1.getUserCode()+" 密码是："+userCheck1.getPassword()+"。";
                    }
                    if(userCheck.getStatus().equals("3")){
                        status = "拒绝。原因是："+userCheck.getRemarks();
                    }
                    String msg = userCheck1.getUserName()+"您好，您的审核结果是："+status+"";
                    EmailUtil.sendEmail(hostName,port,form,to,"电梯动态安全监管系统注册审核结果",msg,password);
                }catch(Exception e){
                    logger.error("根据："+to+"，邮件发送失败！",e);
                }

            }

         }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("审核用户注册 失败"+e.getMessage(), e);
            return ResultUtil.returnError("注册失败，系统异常",null);
        }
        return ResultUtil.returnSuccess("注册成功",null);
    }

    /***
     * 企业用户注册
     * @param partyCheck
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> registerParty(PartyCheck partyCheck) {
        try {
            /**
             * 处理注册时，字段前后有空格
             */
            partyCheck.setUserCode(partyCheck.getUserCode().trim());
            partyCheck.setPartyName(partyCheck.getPartyName().trim());

            SystemUser systemUser = userMapp.findUserPartyByUserCode(partyCheck.getUserCode());
            if(systemUser!=null){
                return ResultUtil.returnError("用户名:"+partyCheck.getUserCode()+" 已存在！",null);
            }
            //查询企业是否注册
            PartyCheck partyCheck1 = partyCheckMapp.queryByPartyName(partyCheck.getPartyName());
            if(partyCheck1!=null && partyCheck1.getStatus().equals("2")){
                return ResultUtil.returnError("单位:"+partyCheck.getPartyName()+" 已申请过，且已审批通过！",null);
            }

            if( null!=partyCheck.getBusinessLicenseImg()
                    && !partyCheck.getBusinessLicenseImg().equals("")
                    && partyCheck.getBusinessLicenseImg()!="null"){
                //通用文字识别营业执照，与填写项进行比较
                Map resmap = AipUtil.checkBussinessImg(environment.getProperty("upload",String.class)+partyCheck.getBusinessLicenseImg(),partyCheck.getPartyName(),partyCheck.getCorporation(),partyCheck.getCreditCode());
                if(resmap!=null){
                    boolean hasPartyName = Boolean.parseBoolean(resmap.get("hasPartyName")+"");
                    boolean hasCorporation = Boolean.parseBoolean(resmap.get("hasCorporation")+"");
                    boolean hasCreditCode = Boolean.parseBoolean(resmap.get("hasCreditCode")+"");
                    String errorMessage = "";
                    if(!hasPartyName){
                        errorMessage += "公司名称与营业执照中的不一致。";
                    }
                    if(!hasCorporation){
                        errorMessage += "法人名字与营业执照中的不一致。";
                    }
                    if(!hasCreditCode){
                        errorMessage += "信用代码与营业执照中的不一致。";
                    }
                    if(errorMessage.length()>0){
                        return ResultUtil.returnError(errorMessage,null);
                    }

                }else{
                    return ResultUtil.returnError("请上传清晰完整的营业执照照片",null);
                }
            }

            //设置注册日期
            partyCheck.setStartTime(new Date());
            //设置审核状态
            partyCheck.setStatus("1");
            if(!"4".equals(partyCheck.getPartyType())){
                Party p = partyMapp.queryByName(partyCheck.getPartyName());
                if(p!=null){
//                    partyCheckMapp.insert(partyCheck);
                    partyCheck.setStatus("2");
                    partyCheck.setRemarks("系统自动审批通过");
                    return checkRegisterPartyAuto(partyCheck);
                }else{
                    return ResultUtil.returnError("请联系所在地的特种设备安全监管部门,在单位备案后可注册",null);
                }
            }else{ //监管部门申请
                partyCheckMapp.insert(partyCheck);
                return ResultUtil.returnSuccess("注册成功请等待审批",null);
            }

        }catch (Exception e){
            logger.error("审核企业注册 失败"+e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }

    }

    /**
     * 企业用户审核
     * @param partyCheck
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> checkRegisterParty(PartyCheck partyCheck) {

        try {
            //查询用户是否存在
            PartyCheck partyCheck1 = partyCheckMapp.queryById(partyCheck.getId().toString());
            if(partyCheck1==null){
                return ResultUtil.returnError("用户:"+partyCheck.getUserCode()+" 不存在！",null);
            }
            //审核通过才记录到系统中
            if(partyCheck.getStatus().equals("2")){
                //用户名密码添加到用户登陆表（sys_user）其他信息添加到用户表user
                ExtSysUser sysUser = new ExtSysUser();
                BeanCopUtil.converJavaBean(sysUser,partyCheck1);
                //企业用户
                sysUser.setUserName(sysUser.getUserCode());
                sysUser.setType("party");
                sysUser.setUserState("1");
                userMapp.add(sysUser);
                Party party = new Party();
                //把partyCheck1中的值赋值给party
                BeanCopUtil.converJavaBean(party,partyCheck1);
                Party party1 = partyMapp.queryByName(party.getPartyName());
                //如果是导入的就更新
                if(party1!=null){
                     party.setId(party1.getId());
                     party.setParentId(party1.getParentId());
                     partyMapp.update(party);
                }else{
                    partyMapp.insert(party);
                }
                //设置检查和那个机构关联删除用
                partyCheck1.setPartyId(party.getId().toString());
                //设置用户和机构的关联关系
                PartyUser partyUser = new PartyUser();
                partyUser.setPartyId(party.getId()+"");
                partyUser.setUserId(sysUser.getId()+"");
                partyUserMapp.insert(partyUser);
                //添加角色1默认是管理员
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(Integer.parseInt(sysUser.getId().toString()));
                //设置为管理员
                if ("1".equals(party.getPartyType())) {
                    sysUserRole.setRoleId(14);
                }
                else if("2".equals(party.getPartyType())){
                    sysUserRole.setRoleId(13);
                }
                else if("3".equals(party.getPartyType())){
                    sysUserRole.setRoleId(15);
                }
                else if("4".equals(party.getPartyType())){
                    sysUserRole.setRoleId(12);
                }

                sysUserRoleMapp.insert(sysUserRole);
                //添加资讯
                //监管部门1(123)  使用单位 2(123) 维保单位 3(123)
                //('1', '行业资讯', '行业资讯'), ('2', '法律法规', '法律法规'), ('3', '工作资讯', '工作资讯')
                //info_name,urls,info_type_id
                if(partyCheck.getPartyType().equals("1")||
                        partyCheck.getPartyType().equals("2")||
                        partyCheck.getPartyType().equals("4")){

                    for(int i=0;i<3;i++){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("partyTypeId",partyCheck.getPartyType());
                        map.put("infoTypeId",i+1);
                        List<InfoAttachment> list = infoAttachmentMapp.queryByType(map);
                        if(list!=null && list.size()>0){
                            for(int j=0;j<list.size();j++){
                                ExtInformation extInformation = new ExtInformation();
                                //标题
                                extInformation.setTitle(list.get(j).getInfoName());
                                extInformation.setCreateUserId(sysUser.getId());
                                extInformation.setCreatePartyId(party.getId());
                                extInformation.setFileUrls("information/"+list.get(j).getUrls());
                                extInformation.setInfoTypeId(Long.parseLong(list.get(j).getInfoTypeId().toString()));
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                                extInformation.setCreateTime(simpleDateFormat.format(new Date()));
                                extInformation.setIsInit("1");
                                informationMapp.add(extInformation);
                            }
                        }
                    }
                }
                calcParty(party);
            }
            //更新 申请记录的状态
            partyCheck1.setSuccessTime(new Date());
            partyCheck1.setStatus(partyCheck.getStatus());
            partyCheck1.setRemarks(partyCheck.getRemarks());
            partyCheckMapp.update(partyCheck1);
            try{
                //发送邮件
                String hostName = environment.getProperty("email.hostName",String.class);
                Integer port = environment.getProperty("email.port",Integer.class);
                String  form = environment.getProperty("email.form",String.class);
                String password = environment.getProperty("email.password",String.class);
                String  to  = partyCheck1.getContactsEmile();
                String status =  "";
                if(partyCheck.getStatus().equals("1")){
                    status = "申请中。";
                }
                if(partyCheck.getStatus().equals("2")){
                    status = "通过。您的账号是："+partyCheck1.getUserCode()+" 密码是："+partyCheck1.getPassword()+"。";
                }
                if(partyCheck.getStatus().equals("3")){
                    status = "拒绝。原因是："+partyCheck1.getRemarks();
                }
                String msg = partyCheck1.getPartyName()+"您好，您的审核结果是："+status+"";
                EmailUtil.sendEmail(hostName,port,form,to,"电梯动态安全监管系统注册审核结果",msg,password);
            }catch(Exception e){
                logger.error("发邮件失败"+e.getMessage(),e);
            }

        }catch (Exception e){
            logger.error("审核企业注册 失败"+e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("注册失败，系统异常",null);
        }
        return ResultUtil.returnSuccess("注册成功",null);
    }

    /**
     * 企业用户审核
     * @param partyCheck
     * @return
     */
    @Transactional
    public Map<String, Object> checkRegisterPartyAuto(PartyCheck partyCheck) {

        try {
            //查询用户是否存在

            //审核通过才记录到系统中
            if(partyCheck.getStatus().equals("2")){
                //用户名密码添加到用户登陆表（sys_user）其他信息添加到用户表user
                ExtSysUser sysUser = new ExtSysUser();
                BeanCopUtil.converJavaBean(sysUser,partyCheck);
                //企业用户
                sysUser.setUserName(sysUser.getUserCode());
                sysUser.setType("party");
                sysUser.setUserState("1");
                userMapp.add(sysUser);
                Party party = new Party();
                //把partyCheck1中的值赋值给party
                BeanCopUtil.converJavaBean(party,partyCheck);
                Party party1 = partyMapp.queryByName(party.getPartyName());
                //如果是导入的就更新
                if(party1!=null){
                    party.setId(party1.getId());
                    party.setParentId(party1.getParentId());
                    partyMapp.update(party);
//                    if ("1".equals(party.getPartyType()) || "2".equals(party.getPartyType())) {
//                        calcParty(party);
//                    }
                }else{
                    partyMapp.insert(party);
                }
                //设置检查和那个机构关联删除用
                partyCheck.setPartyId(party.getId().toString());
                //设置用户和机构的关联关系
                PartyUser partyUser = new PartyUser();
                partyUser.setPartyId(party.getId()+"");
                partyUser.setUserId(sysUser.getId()+"");
                partyUserMapp.insert(partyUser);
                //添加角色1默认是管理员
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(Integer.parseInt(sysUser.getId().toString()));
                //设置为管理员
                if ("1".equals(party.getPartyType())) {
                    sysUserRole.setRoleId(14);
                }
                else if("2".equals(party.getPartyType())){
                    sysUserRole.setRoleId(13);
                }
                else if("3".equals(party.getPartyType())){
                    sysUserRole.setRoleId(15);
                }
                else if("4".equals(party.getPartyType())){
                    sysUserRole.setRoleId(12);
                }else{
                    sysUserRole.setRoleId(12);
                }

                sysUserRoleMapp.insert(sysUserRole);
                //添加资讯
                //监管部门1(123)  使用单位 2(123) 维保单位 3(123)
                //('1', '行业资讯', '行业资讯'), ('2', '法律法规', '法律法规'), ('3', '工作资讯', '工作资讯')
                //info_name,urls,info_type_id
                if(partyCheck.getPartyType().equals("1")||
                        partyCheck.getPartyType().equals("2")||
                        partyCheck.getPartyType().equals("4")){

                    for(int i=0;i<3;i++){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("partyTypeId",partyCheck.getPartyType());
                        map.put("infoTypeId",i+1);
                        List<InfoAttachment> list = infoAttachmentMapp.queryByType(map);
                        if(list!=null && list.size()>0){
                            for(int j=0;j<list.size();j++){
                                ExtInformation extInformation = new ExtInformation();
                                //标题
                                extInformation.setTitle(list.get(j).getInfoName());
                                extInformation.setCreateUserId(sysUser.getId());
                                extInformation.setCreatePartyId(party.getId());
                                extInformation.setFileUrls("information/"+list.get(j).getUrls());
                                extInformation.setInfoTypeId(Long.parseLong(list.get(j).getInfoTypeId().toString()));
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                                extInformation.setCreateTime(simpleDateFormat.format(new Date()));
                                extInformation.setIsInit("1");
                                informationMapp.add(extInformation);
                            }
                        }
                    }
                }
                calcParty(party);
            }
            //更新 申请记录的状态
            partyCheck.setSuccessTime(new Date());
            partyCheckMapp.insert(partyCheck);
            //发送邮件
            String  to  = partyCheck.getContactsEmile();
            String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern p = Pattern.compile(regEx1);
            Matcher m = p.matcher(to);
            if(m.matches()){
                String hostName = environment.getProperty("email.hostName",String.class);
                Integer port = environment.getProperty("email.port",Integer.class);
                String  form = environment.getProperty("email.form",String.class);
                String password = environment.getProperty("email.password",String.class);
                String status =  "";
                if(partyCheck.getStatus().equals("1")){
                    status = "申请中。";
                }
                if(partyCheck.getStatus().equals("2")){
                    status = "通过。您的账号是："+partyCheck.getUserCode()+" 密码是："+partyCheck.getPassword()+"。";
                }
                if(partyCheck.getStatus().equals("3")){
                    status = "拒绝。原因是："+partyCheck.getRemarks();
                }
                String msg = partyCheck.getPartyName()+"您好，您的审核结果是："+status+"";
                EmailUtil.sendEmail(hostName,port,form,to,"电梯动态安全监管系统注册审核结果",msg,password);
            }

        }catch (Exception e){
            logger.error("注册时，自动审核失败！",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("注册失败，系统异常",null);
        }
        return ResultUtil.returnSuccess("注册成功",null);
    }
    
    private void calcParty(Party party) throws Exception {
    	if ("1".equals(party.getPartyType()) && party.getZzzs() != null) {
    		PromotionUtil.calcParty(promotionMapp,  5, "1", party.getId(), "在单位信息注册中上传单位资质证书", "1-1");
        } else if ("2".equals(party.getPartyType()) && party.getZzzs() != null) {
        	PromotionUtil.calcParty(promotionMapp, 5, "2", party.getId(), "在单位信息注册中上传单位资质证书", "1-1");
        } 
    	if ("1".equals(party.getPartyType()) && party.getZzdj() != null) {
    		PromotionUtil.calcParty(promotionMapp, 5, "1", party.getId(), "在单位信息注册中填写单位资质等级", "2-1");
        } else if ("2".equals(party.getPartyType()) && party.getZzdj() != null) {
        	PromotionUtil.calcParty(promotionMapp, 5, "2", party.getId(), "在单位信息注册中填写单位资质等级", "2-1");
        }
    }

//    private void calcParty(Party party) throws Exception {
//    	Map<String, Object> map = new HashMap<>();
//		map.put("type", party.getPartyType());
//		map.put("userId", String.valueOf(party.getId()));
//		Promotion promotion = promotionMapp.findById(map);
//		PromotionParty promotionParty = promotionMapp.findPartyById(party.getId());
//		String month = new SimpleDateFormat("yyyyMM").format(new Date());
//		Map<String, Object> map2 = new HashMap<>();
//		map2.put("month", month);
//		map2.put("userId", String.valueOf(party.getId()));
//		PromotionPartyAdded promotionPartyAdded = promotionMapp.findPartyAddedById(map2);
//
//		Integer empiricValueAdded = 0;
//		if (null != party.getCorporation() && "0".equals(promotionParty.getCorporation())) {
//			promotionParty.setCorporation("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("法人代表信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getTelephone() && (promotionParty.getTelephone()==null || "0".equals(promotionParty.getTelephone()))) {
//			promotionParty.setTelephone("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("单位电话信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContacts() && "0".equals(promotionParty.getContacts())) {
//			promotionParty.setContacts("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContactsWork() && "0".equals(promotionParty.getContactsWork())) {
//			promotionParty.setContactsWork("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人职务信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContactsCard() && "0".equals(promotionParty.getContactsCard())) {
//			promotionParty.setContactsCard("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人身份证号码信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContactsPhone() && "0".equals(promotionParty.getContactsPhone())) {
//			promotionParty.setContactsPhone("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人电话信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContactsEmile() && "0".equals(promotionParty.getContactsEmile())) {
//			promotionParty.setContactsEmile("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人邮箱信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContactsMobile() && "0".equals(promotionParty.getContactsMobile())) {
//			promotionParty.setContactsMobile("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人手机信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		if (null != party.getContactsAddress() && "0".equals(promotionParty.getContactsAddress())) {
//			promotionParty.setContactsAddress("1");
//			empiricValueAdded += 100;
//			PromotionRecord promotionRecord = new PromotionRecord();
//			promotionRecord.setUserId(party.getId() + "");
//			promotionRecord.setType(party.getPartyType());
//			promotionRecord.setEmpiricItem("联系人地址信息");
//			promotionRecord.setAddedTime(PromotionUtil.getTime());
//			promotionRecord.setEmpiricValue(100);
//			promotionMapp.insertRecord(promotionRecord);
//		}
//		promotionMapp.updateParty(promotionParty);
//		promotion.setEmpiricValue(empiricValueAdded + promotion.getEmpiricValue());
//		promotionMapp.update(promotion);
//		// 记录增加的积分值
//		if (null != promotionPartyAdded && promotionPartyAdded.getId() != null) {
//			promotionPartyAdded.setEmpiricValueAdded(empiricValueAdded + promotionPartyAdded.getEmpiricValueAdded());
//			promotionMapp.updatePartyAdded(promotionPartyAdded);
//		} else {
//			promotionPartyAdded = new PromotionPartyAdded();
//			promotionPartyAdded.setMonth(month);
//			promotionPartyAdded.setUserId(String.valueOf(party.getId()));
//			promotionPartyAdded.setEmpiricValueAdded(empiricValueAdded);
//			promotionMapp.insertPartyAdded(promotionPartyAdded);
//		}
//    }

    @Override
    public Map<String, Object> queryUserCheckList(UserCheck userCheck) {
        List<UserCheck> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<UserCheck> page = PageHelper.startPage(userCheck.getCurrentPage(), userCheck.getPageSize());
            list = userCheckMapp.queryUserCheckList(userCheck);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    @Override
    public Map<String, Object> queryPartyCheckList(PartyCheck partyCheck) {
        List<PartyCheck> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<PartyCheck> page = PageHelper.startPage(partyCheck.getCurrentPage(), partyCheck.getPageSize());
            list = partyCheckMapp.queryPartyCheckList(partyCheck);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    @Override
    public Map<String, Object> resetPassword(String email) {
        try {
            if(email==null||email.length()<=0){
                throw new Exception("邮箱不能为空");
            }
            String hostName = environment.getProperty("email.hostName",String.class);
            Integer port = environment.getProperty("email.port",Integer.class);
            String  form = environment.getProperty("email.form",String.class);
            String password = environment.getProperty("email.password",String.class);
            String  to  = email;
            //根据id查询出用户的信息
            List<Party> partyList = partyMapp.queryByEmail(email);
            if(partyList!=null && partyList.size()>0){
                //查询邮箱下的用户
                for(int i=0;i<partyList.size();i++){

                    List<SystemUser> systemUser = userMapp.queryByPartyId(partyList.get(i).getId().toString());
                    if(systemUser!=null && systemUser.size()>0){
                        for(int j=0;j<systemUser.size();j++){
                            String msg="您的账号是："+systemUser.get(j).getUserName()+" 密码是："+systemUser.get(i).getPassword()+",请妥善保管！";
                            EmailUtil.sendEmail(hostName,port,form,to,"电梯监管系统密码找回结果",msg,password);
                        }

                    }

                }
            }
            //查询用户的
            List<SystemUser> usersList = userMapp.queryByEmail(email);
            if(usersList!=null && usersList.size()>0){
                for(int i=0;i<usersList.size();i++){
                        String msg="您的账号是："+usersList.get(i).getUserName()+" 密码是："+usersList.get(i).getPassword()+",请妥善保管！";
                        EmailUtil.sendEmail(hostName,port,form,to,"电梯监管系统密码找回结果",msg,password);
                }
            }
            if(partyList==null&&usersList==null){
                throw new Exception("请输入您注册时候填写的邮箱");
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 导入人员
     * @param file
     * @param partyId
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> importPartyPerson(MultipartFile file, String partyId,String partyType) {
        try {
            List<List<Object>> list = ExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
            //获取导入的信息做处理
            if (list != null && list.size() > 0) {
                // 判断角色
                if ("4".equals(partyType)) {
                    if(list.size()>1){
                        for (int i = 1; i < list.size(); i++) {
                            ExtSysUser p = new ExtSysUser();
                            int j = i + 2;

                            List<Object> objects = list.get(i);
                            if (objects.size() ==list.get(0).size()) {
                                // 登录名
                                if (objects.get(0) != null && StringUtils.isNotEmpty(objects.get(0).toString().trim())) {
                                    List<SystemUser> userCodeList = userMapp.queryUserCodeList(objects.get(0).toString().trim());
                                    if (userCodeList != null && userCodeList.size() > 0) {
                                        throw new Exception("登录名： " + objects.get(0).toString().trim() + " 已经被使用，请重新输入！");
                                    }
                                    p.setUserCode(objects.get(0).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行登录名为空，请填写");
                                }
                                // 密码
                                if (objects.get(1) != null && StringUtils.isNotEmpty(objects.get(1).toString().trim())) {
                                    p.setPassword(objects.get(1).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行密码为空，请填写");
                                }

                                // 用户姓名
                                if (objects.get(2) != null && StringUtils.isNotEmpty(objects.get(2).toString().trim())) {
                                    p.setUserName(objects.get(2).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行用户姓名为空，请填写");
                                }
                                // 用户类型
                                if (objects.get(3) != null && StringUtils.isNotEmpty(objects.get(3).toString().trim())) {
                                    ExtSystemRole role = new ExtSystemRole();
                                    role.setRoleName(objects.get(3).toString().trim());
                                    SystemRole systemRole = systemRoleMapp.queryByName(role);
                                    if (systemRole != null) {
                                        p.setRoleId(String.valueOf(systemRole.getId()));
                                    } else {
                                        throw new Exception(objects.get(3).toString().trim() + " 用户类型系统未找到，请联系管理员");
                                    }
                                } else {
                                    throw new Exception("表格第 " + j + " 行用户类型为空，请填写");
                                }
                                // 持证类型
                                if (objects.get(4) != null && StringUtils.isNotEmpty(objects.get(4).toString().trim())) {
                                    p.setCardType(objects.get(4).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行持证类型为空，请填写");
                                }
                                // 身份证
                                if (objects.get(5) != null && StringUtils.isNotEmpty(objects.get(5).toString().trim())) {
                                    SystemUser systemUser = userMapp.queryByCardNumber(objects.get(5).toString().trim());
                                    if (systemUser != null) {
                                        throw new Exception("身份证号:" + objects.get(5).toString().trim() + "已存在");
                                    }
                                    p.setCardNumber(objects.get(5).toString().trim());
                                    p.setCardTypeNumber(objects.get(5).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行身份证为空，请填写");
                                }
                                // 工号
                                if (objects.get(6) != null && StringUtils.isNotEmpty(objects.get(6).toString().trim())) {
                                    SystemUser user = userMapp.queryByWorkNumber(objects.get(6).toString().trim());
                                    if (null != user) {
                                        throw new Exception("工号" + objects.get(6).toString().trim() + "被使用!");
                                    }
                                    p.setWorkNumber(objects.get(6).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行工号为空，请填写");
                                }
                                // 手机号码
                                if (objects.get(7) != null && StringUtils.isNotEmpty(objects.get(7).toString().trim())) {
                                    p.setPhone(objects.get(7).toString().trim());
                                } else {
                                    throw new Exception("表格第 " + j + " 行手机号码为空，请填写");
                                }
                            } else {
                                int o = i + 2;
                                throw new Exception("表格第 " + o + " 行内容填写不完整，请填写表格信息");
                            }
                            p.setType("user");
                            p.setUserState("1");
                            userMapp.add(p);
                            //设置用户和机构的关系
                            PartyUser partyUser = new PartyUser();
                            partyUser.setPartyId(partyId);
                            partyUser.setUserId(p.getId() + "");
                            partyUserMapp.insert(partyUser);

                            /**
                             * 插入用户与角色的关系
                             */
                            if(p.getRoleId() != null){
                                SysUserRole sysUserRole = new SysUserRole();
                                sysUserRole.setRoleId(Integer.parseInt(p.getRoleId()));
                                sysUserRole.setUserId(Integer.parseInt(p.getId().toString()));
                                sysUserRoleMapp.insert(sysUserRole);
                            }
                        }
                    }else{
                        throw new Exception("表格内容为空，请填写表格信息");
                    }
                } else {
                    // 之前的老代码
                    for (int i = 0; i < list.size(); i++) {
                        List listObject = list.get(i);
                        if (listObject != null && listObject.size() > 0 && (listObject.get(0) + "").equals("姓名")) {
                            continue;
                        }

                        if (listObject != null && listObject.size() > 1) {
                            ExtSysUser p = new ExtSysUser();

                            if (listObject.get(0) != null && listObject.get(0).toString().trim().length() > 0) {
                                p.setUserName(listObject.get(0).toString());
                            } else {
                                break;
                            }
                            if (listObject.get(1) != null && !"".equals(listObject.get(1).toString().trim())) {
                                SystemUser systemUser = userMapp.queryByCardNumber(listObject.get(1).toString());
                                if (systemUser != null) {
                                    throw new Exception("身份证号" + listObject.get(1).toString() + "已存在");
                                }
                                p.setCardNumber(listObject.get(1).toString());
                            }
                            if (listObject.get(2) != null && !"".equals(listObject.get(2).toString().trim())) {

                                p.setCardTypeNumber(listObject.get(2).toString());
                            }
                            p.setType("user");
                            p.setUserState("0");
                            userMapp.add(p);
                            //设置用户和机构的关系
                            PartyUser partyUser = new PartyUser();
                            partyUser.setPartyId(partyId);
                            partyUser.setUserId(p.getId() + "");
                            partyUserMapp.insert(partyUser);
                        }
                    }
                }
            }
            Party p = partyMapp.queryById(partyId);
            ImportRecord importRecord = new ImportRecord();
            importRecord.setUserId(partyId);
            importRecord.setType(p.getPartyType());
            int num = importRecordMapp.findByIdList(importRecord);
            if (num == 0) {
                importRecord.setImportDt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
                importRecordMapp.add(importRecord);
            }
        } catch (Exception e) {
            logger.error("导入人员失败: " + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError(e.getMessage(), null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 检测人脸
     * @param user
     * @param file
     * @return
     */
    @Override
    public Map<String, Object> checkFace(SystemUser user, MultipartFile file) {
        try{
            //检测是否是人脸
            JSONObject jsonObject = FaceUtile.FaceDetect(file.getBytes());
            JSONArray getJSONArray = jsonObject.getJSONArray("result");
            if(getJSONArray.length()>0){
                JSONObject a = getJSONArray.getJSONObject(0);
                Double d = a.getDouble("face_probability");
                if(d>0.7){
                    try{
                        SystemUser u = userMapp.queryByUserCode(user.getUserCode());
                        if(u==null){
                            return ResultUtil.returnError(user.getUserCode()+"用户不存在",null);
                        }
                        //对比人脸
                        byte[][] b ={file.getBytes(),FileUploadUtil.getBytes(environment.getProperty("upload",String.class)+u.getFaceUrl())};
                        JSONObject response  = FaceUtile.FaceMatch(b);
                        String error_msg =null;
                        try{
                            error_msg = response.getString("error_msg");
                            return ResultUtil.returnError(error_msg, null);
                        }catch (Exception e){
                            JSONArray getPathJSONArray = response.getJSONArray("result");
                            if(getPathJSONArray.getJSONObject(0).length()>0){
                                JSONObject jsonObjectPath = getPathJSONArray.getJSONObject(0);
                                double dd = jsonObjectPath.getDouble("score");
                                if(dd>70){
                                    return ResultUtil.returnSuccess("校验成功", u);
                                }else{
                                    return ResultUtil.returnError("人脸对比失败", null);
                                }
                            }else{
                                return ResultUtil.returnError("请选择人脸",null);
                            }
                        }
                    }catch (Exception e){
                        return ResultUtil.returnError("人脸对比失败", null);
                    }
                }
            }
            return ResultUtil.returnError("请选择人脸",null);
        }catch (Exception e){
            logger.error("人脸对比失败: "+e.getMessage(),e);
            return ResultUtil.returnError("人脸对比失败",null);
        }
    }


    /**
     * 根据机构查询用户列表
     * @param partyId
     * @return
     */
    @Override
    public Map<String, Object> queryByPartyId(String partyId) {
        List<SystemUser> userList =null;
        try {
            userList = userMapp.queryByPartyId(partyId);
        } catch (Exception e) {
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",userList);
    }


    /**
     * 获取一级菜单
     * @param users
     * @return
     */
    public List<ExtTree> findParent(List<ExtSysUser> users){
        List<ExtTree> list = new ArrayList<ExtTree>();
        List<ExtTree> resultList = new ArrayList<ExtTree>();
        //获取第一层菜单
        for(int i=0;i<users.size();i++){
            if(users.get(i).getParentId()==0){
                ExtTree extTree = new ExtTree();
                extTree.setPartyId(users.get(i).getPartyId());
                extTree.setAuthorName(users.get(i).getAuthorName());
                extTree.setAuthorIcon(users.get(i).getAuthorIcon());
                extTree.setAuthorId(users.get(i).getAuthorId());
                extTree.setParentId(users.get(i).getParentId());
                extTree.setAuthorUrl(users.get(i).getAuthorUrl());
                //extTree.setExtSysUser(users.get(i));
                list.add(extTree);
            }
        }
        //获取菜单下的菜单
        for(int i=0;i<list.size();i++){
            ExtTree extTree = new ExtTree();
            extTree.setPartyId(list.get(i).getPartyId());
            extTree.setAuthorName(list.get(i).getAuthorName());
            extTree.setAuthorIcon(list.get(i).getAuthorIcon());
            extTree.setAuthorId(list.get(i).getAuthorId());
            extTree.setParentId(list.get(i).getParentId());
            extTree.setAuthorUrl(list.get(i).getAuthorUrl());
            extTree.setChildList(findChild(users,list.get(i).getAuthorId()));
            resultList.add(extTree);
        }
        return resultList;
    }

    /**
     * 获取下级菜单
     * @return
     */
    public List<ExtTree> findChild(List<ExtSysUser> list, long parentId){
        List<ExtTree> resultList = new ArrayList<ExtTree>();
         for (int i=0;i<list.size();i++){
             if(list.get(i).getParentId().equals(parentId)){
                 ExtTree extTree = new ExtTree();
                 extTree.setPartyId(list.get(i).getPartyId());
                 extTree.setAuthorName(list.get(i).getAuthorName());
                 extTree.setAuthorIcon(list.get(i).getAuthorIcon());
                 extTree.setAuthorId(list.get(i).getAuthorId());
                 extTree.setParentId(list.get(i).getParentId());
                 extTree.setAuthorUrl(list.get(i).getAuthorUrl());
                 extTree.setChildList(findChild(list,list.get(i).getAuthorId()));
                 resultList.add(extTree);
             }
         }

       return resultList;
    }



    /**
     * 更新用户状态
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> updateUserState(Map user) {
        try {
        	user.put("updateTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            int i = userMapp.updateUserState(user);
        } catch (Exception e) {
            return ResultUtil.returnError("更改失败"+e.getMessage(),null);
        }finally {
            PointDefendInfoCache infoCache = new PointDefendInfoCache();
            //通过Id获取用户信息，判断是多证还是单证
            try {
                String id =String.valueOf (user.get("id"));

                ExtSysUser extSysUser = userMapp.findById(id);

                PointDefend defend = SystemPointUtil.multipleCard(infoCache, extSysUser.getCardType(), "add_double_cards", "add_one_cards", "add_none_cards");

                // 获取积分
                Integer mark = extSysUser.getMark();
                if (mark == null) {
                    mark = 0;
                }
                // 计算积分
                int round = 0;
                // 获取状态  0 停用 1 在用
                String function = "启用";

                String userState = (String) user.get("userState");
                if("0".equals(userState)){
                    round = (int) (mark - defend.getMark());
                    function = "停用";
                }else{
                    round = (int) (mark + defend.getMark());
                }
                // 更新积分
                String userId = String.valueOf(extSysUser.getId());
                int i = pointFlowMapp.updateMark(round, userId);
                SystemPointUtil.insertFlow(pointFlowMapp,i,defend,round,extSysUser.getUserName(),extSysUser.getPartyName(),function);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return ResultUtil.returnSuccess("更改成功",null);
    }

    /**
     * 更新用户所属机构
     * @param partyUser
     * @return
     */
    @Override
    public Map<String, Object> updateUserParty(Map partyUser) {
        try {
            userMapp.updateUserParty(partyUser);
        } catch (Exception e) {
            return ResultUtil.returnError("转移失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("转移成功",null);
    }

    @Override
    public Map<String, Object> updateUserPhone(Map user) {

        try {
            userMapp.updateUserPhone(user);
        } catch (Exception e) {
            return ResultUtil.returnError("更新用户手机号失败："+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("更新手机号成功",null);
    }

    @Override
    public Map<String, Object> updateUserPwd(Map user) {
        try {
            SystemUser systemUser = userMapp.findById(user.get("id")+"");
            if(null==systemUser){
                return ResultUtil.returnError("修改失败，无此用户",null);
            }
            if(!systemUser.getPassword().equals(user.get("oldpwd"))){
                return ResultUtil.returnError("旧密码错误",null);
            }
            int i = userMapp.updateUserPwd(user);
        } catch (Exception e) {
            return ResultUtil.returnError("修改失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("修改成功",null);
    }

    @Override
    public Map<String, Object> getVersion() {
        SysVersion sysVersion = null;
        try {
            sysVersion = userMapp.getVersion();
            if(null==sysVersion){
                return ResultUtil.returnError("查询失败，没有版本号",null);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("失败",null);
        }
        return ResultUtil.returnSuccess("成功",sysVersion);
    }


    @Override
    public Map<String, Object> findTomy(UserMetastasis userMetastasis) {
        List<ExtUserMetastasis> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtUserMetastasis> page = PageHelper.startPage(userMetastasis.getCurrentPage(), userMetastasis.getPageSize());
            list = userMetastasisMapp.findTomy(userMetastasis.getToId());
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败",null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    @Override
    public Map<String, Object> addMeatasis(UserMetastasis userMetastasis) {
        try{
        	List<UserMetastasis> tempList = userMetastasisMapp.findMyTransfer(userMetastasis.getUserId());
        	if (null != tempList && tempList.size() > 0) {
                return ResultUtil.returnError("待转移用户已存在未审批申请！",null);
        	}
        	userMetastasis.setApplyTime(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            userMetastasisMapp.insert(userMetastasis);
        }catch(Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("新增失败",null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> updateMeatasis(Map param) {
        try{
        	UserMetastasis userMetastasis = new UserMetastasis();
        	userMetastasis.setId(Long.valueOf(param.get("id") + ""));
        	userMetastasis.setState(param.get("state") + "");
        	userMetastasis.setRemark(param.get("remark") + "");
            userMetastasisMapp.update(userMetastasis);
        }catch(Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("更新失败",null);
        }
        try{
            //发送邮件
            String hostName = environment.getProperty("email.hostName",String.class);
            Integer port = environment.getProperty("email.port",Integer.class);
            String  form = environment.getProperty("email.form",String.class);
            String password = environment.getProperty("email.password",String.class);
            String  to  = param.get("email") + "";
            String msg = param.get("userName") + " 您好，您在电梯安全动态监管/智慧管理系统向" + param.get("toName") + "公司发起的用户转移申请已经通过审核！";
            EmailUtil.sendEmail(hostName,port,form,to,"电梯动态安全监管系统转移审核结果",msg,password);
        }catch(Exception e){
            logger.error("发邮件失败"+e.getMessage(),e);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 通过Id获取积分
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getMarkById(Long id) {
        Map<String,Object> map = new HashMap<>();
        try{
           map = userMapp.getMarkById(id);
        }catch(Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败",null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }


}
